#include "EditorCore/Tools/MoveTool.h"
#include "EditorCore/Visitors/EntityUnderPositionFinder.h"

using namespace cmn;
using namespace input;

namespace editor_core {

	MoveTool::MoveTool( IDocument* document ) :
		m_document( document ),
		m_targetEntity( 0 ),
		m_tempAction( 0 )
	{}

	IAction* MoveTool::Activate() { return 0; }
	IAction* MoveTool::Deactivate() { return 0; }

	IAction* MoveTool::ProcessMouseButtonPress( MouseButtonEventArgs* mouseButtonEventArgs ) {
		if( mouseButtonEventArgs->GetButton() == MouseButton::Left ) {
			Vec2 mousePos = mouseButtonEventArgs->GetMouseState().GetPosition();

			m_targetEntity = EntityUnderPositionFinder::FindEntityUnderCursor( m_document->GetRootEntity(), mousePos );

			m_mousePosStart = mousePos;
			m_mousePosEnd = mousePos;
		}
		return 0;
	}

	IAction* MoveTool::ProcessMouseMove( MouseMoveEventArgs* mouseMoveEventArgs ) {
		if( m_targetEntity == 0 )
			return 0;

		Mouse mouse = mouseMoveEventArgs->GetMouseState();

		if( mouse.GetButtonState( MouseButton::Left ) == ButtonState::Released )
			return 0;

		if( m_tempAction != 0 ) {
			m_tempAction->Undo();
			delete m_tempAction;
			m_tempAction = 0;
		}

		Vec2 mousePos = mouse.GetPosition();
		m_mousePosEnd = mousePos;

		m_tempAction = new MoveAction( m_targetEntity, m_mousePosEnd - m_mousePosStart );
		m_tempAction->Do();
		return 0;
	}

	IAction* MoveTool::ProcessMouseButtonRelease( MouseButtonEventArgs* mouseButtonEventArgs ) {
		if( m_targetEntity == 0 )
			return 0;

		if( mouseButtonEventArgs->GetButton() == MouseButton::Left ) {
			if( m_tempAction != 0 ) {
				m_tempAction->Undo();
				delete m_tempAction;
				m_tempAction = 0;
			}
			IAction* move = new MoveAction( m_targetEntity, m_mousePosEnd - m_mousePosStart );
			m_targetEntity = 0;
			return move;
		}
		return 0;
	}

	IAction* MoveTool::ProcessMouseScroll( MouseScrollEventArgs* mouseScrollEventArgs ) { return 0; }
	IAction* MoveTool::ProcessKeyPress( KeyEventArgs* keyEventArgs ) { return 0; }
	IAction* MoveTool::ProcessKeyRelease( KeyEventArgs* keyEventArgs ) { return 0; }

}
